/* 用户模块的vuex操作 */
import { setStorageToken, getStorageToken, removeStorageToken } from '@/utils/storage'
import { getUserInfo } from '@/api/user' // 获取用户信息api
import { Toast } from 'vant'
export default {
  namespaced: true,
  state: {
    // token: JSON.parse(localStorage.getItem('hm-toutiao-token')) || {}
    token: getStorageToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
      // localStorage.setItem('hm-toutiao-token', JSON.stringify(payload))
      // 设置本地token
      setStorageToken(payload)
    },
    removeToken(state) {
      // 清除vuex中token
      state.token = {}
      // 清除本地token
      removeStorageToken()
    },
    setUserInfo(state, payload) { // 设置用户信息
      state.userInfo = payload
    }
  },
  actions: {
    // 异步发送获取用户信息的请求
    async Actions_getUserInfo(context) {
      try {
        const res = await getUserInfo()
        context.commit('setUserInfo', res.data)
      } catch {
        Toast('获取用户信息失败')
      }
    }
  }
}
